package com.android.dumiaogou.fragment.group;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.adapt.MyDateViewHolder;
import com.android.dumiaogou.fragment.BaseLazyFragment;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlyData;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlySendData;
import com.android.dumiaogou.model.auction.Auction_pastedturnover;
import com.android.dumiaogou.model.auction.Auction_pastedturnoverCallback;
import com.android.dumiaogou.service.WebSocketService;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/1.
 */

public class Fragment_BidHistory extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    private FragmentActivity mcontext;
    private View view;
    private static final String ARG_PARAM1 = "param1";
    private static final String DETAIL_SHOW = "DETAIL_SHOW";
    private String mParam1;
    private boolean networkConnected;

    private WebSocketService service;
    private BroadcastReceiver mBroadcastReceiver;
    private AdaptList adapter;
    private ArrayList<Auction_pastedturnover.ListBean> listdata  = new ArrayList<>();
    private Auction_DetailRecentlySendData recentlySendData = new Auction_DetailRecentlySendData();
    private Auction_DetailRecentlyData recentlyData = new Auction_DetailRecentlyData();
    private ArrayList<Auction_DetailRecentlyData.ListBean> bh_listdata  = new ArrayList<>();;
    private int page =1;
    private Gson gson = new Gson();
    private String gsonstring="";
    String order_sn;
    private int detail_show;
    private AdaptListPost adapterPost;

    /**
     * 最新成交
     */


    public Fragment_BidHistory() {


    }

    public static Fragment_BidHistory newInstance(String order_sn, int detail_show) {
        Fragment_BidHistory fragment = new Fragment_BidHistory();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, order_sn);
        args.putInt(DETAIL_SHOW, detail_show);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            order_sn = getArguments().getString(ARG_PARAM1);
            detail_show = getArguments().getInt(DETAIL_SHOW);
        }
    }



    @Override
    protected void initPrepare() {

        ReFreshData();
    }



    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {

        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            getData();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    private void getData() {
        if(detail_show==2){
            GetDataListData();
        }else {
            recentlySendData.setType("join_log");
            recentlySendData.setOrder_sn(order_sn);
            recentlySendData.setPage(page);
            recentlySendData.setPer_page(10);
            gsonstring = gson.toJson(recentlySendData);
            service.sendMsg(gsonstring);
        }
    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_recycle_bidhistory, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }
    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        getData();
    }

    private void ReFreshData() {
        adapter = new AdaptList(mcontext, bh_listdata,"");
        adapterPost = new AdaptListPost(mcontext, listdata,"");
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        if(detail_show==2){
            mRecyclerView.setAdapter(adapterPost);
        }else {
            broadcastReceive();
            mRecyclerView.setAdapter(adapter);
        }
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page=1;
                    getData();
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }


    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page=1;
        getData();
    }

    //设置广播监听
    private void broadcastReceive() {
        service = WebSocketService.getInstance();

        //service.sendMsg(get_banner);
        // service.sendMsg(get_menus);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //趣买最新出价消息
                if (action.equals(WebSocketService.ACTION_JOINLOG)) {
                    recentlyData = (Auction_DetailRecentlyData) intent.getBundleExtra("bundle5").getSerializable("AuctionJoinLog");
                    ObjectUtils.GetDataNet(clickResetnetwork, progress,1);
                    mRefreshLayout.setRefreshing(false);
                    if (recentlyData.getList() != null && recentlyData.getList().size() > 0) {
                        bh_listdata.clear();
                        for (int i = 0; i < recentlyData.getList().size(); i++) {
                            if (i == 0) {

                                bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "抢先"
                                        , recentlyData.getList().get(i).getMid(),recentlyData.getList().get(i).getUsername(), recentlyData.getList().get(i).getPhoto()
                                        ,recentlyData.getList().get(i).getType(), recentlyData.getList().get(i).getIp(),recentlyData.getList().get(i).getCity(),recentlyData.getList().get(i).getC_time()
                                        ,recentlyData.getList().get(i).getPrice()));
                            } else
                            {

                                bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
                                        , recentlyData.getList().get(i).getMid(),recentlyData.getList().get(i).getUsername(), recentlyData.getList().get(i).getPhoto()
                                        ,recentlyData.getList().get(i).getType(), recentlyData.getList().get(i).getIp(),recentlyData.getList().get(i).getCity(),recentlyData.getList().get(i).getC_time()
                                        ,recentlyData.getList().get(i).getPrice()));
                            }
                        }
//                            if(recentlyData.getList().size()<3)
//                            {
//                                for (int i = recentlyData.getList().size(); i < 3; i++) {
//
//                                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
//                                            ,"","","","","","","",""));
//                                }
//                            }
                        if (page == 1) {
                            adapter.setNewData(bh_listdata);
                        } else {
                            adapter.addData(bh_listdata);
                            adapter.loadMoreComplete();
                        }
                    }
                    else
                    {
                        if(page==1) {
                            noData.setVisibility(View.VISIBLE);
                        }
                        adapter.loadMoreEnd();
                    }
                }
            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService.ACTION_JOINLOG);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);

    }



    /**
     * 商品列表
     */
    private void GetDataListData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        final String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONREJOINLOG ;
        HashMap<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("size","15");
        map.put("order_sn",order_sn);
        MyLog.e("order_sn",order_sn);
        if (networkConnected) {

            HttpUtils.get(address,map, new Auction_pastedturnoverCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(Auction_pastedturnover response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata = new ArrayList<>();
                        if (response.getList() != null&&response.getList().size()>0) {

                            for (int i = 0; i < response.getList().size(); i++) {
                                listdata.add(new Auction_pastedturnover.ListBean(Auction_pastedturnover.ListBean.THREE, response.getList().get(i).getId()
                                        , response.getList().get(i).getOrder_id(), response.getList().get(i).getMid()
                                        ,  response.getList().get(i).getType(),response.getList().get(i).getPrice(), response.getList().get(i).getC_time()
                                        , response.getList().get(i).getUsername(), response.getList().get(i).getMobile()
                                        , response.getList().get(i).getNickname(), response.getList().get(i).getPhoto()
                                        , response.getList().get(i).getCity()));
                            }
                            if (page == 1) {
                                adapterPost.setNewData(listdata);
                            } else {
                                adapterPost.addData(listdata);
                                adapterPost.loadMoreComplete();
                            }
                        } else {
                            if(page==1) {
                                noData.setVisibility(View.VISIBLE);
                            }
                            adapterPost.loadMoreEnd();
                        }
                    }
                }
            });
        }else {
            noData.setVisibility(View.VISIBLE);
            noDataTv.setVisibility(View.VISIBLE);
            ObjectUtils.toast(mcontext, "网络未连接");

        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<Auction_DetailRecentlyData.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptList(FragmentActivity context, List<Auction_DetailRecentlyData.ListBean> data, String type) {
            super(data);
            this.mcontext = context;
            this.type = type;
            addItemType(Auction_pastedturnover.ListBean.THREE, R.layout.item_bidhistory);
        }


        @Override
        protected void convert(MyDateViewHolder holder, Auction_DetailRecentlyData.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case Auction_pastedturnover.ListBean.THREE:
                    ObjectUtils.photoCircle(mContext, mainlistdata.getPhoto(), ((ImageView) holder.getView(R.id.item_detail_bidhistoryimg)));

                    if (holder.getLayoutPosition() == 0) {
                        holder.setTextColor(R.id.aishang_username, getResources().getColor(R.color.red));
                        holder.setText(R.id.aishang_isFirst, "抢先");
                        TextView aishang_isFirst = holder.getView(R.id.aishang_isFirst);
                        holder.setTextColor(R.id.aishang_isFirst, getResources().getColor(R.color.red));
                        holder.setTextColor(R.id.aishang_city, getResources().getColor(R.color.red));
                        holder.setTextColor(R.id.aishang_price, getResources().getColor(R.color.red));
                    } else {
                        holder.setTextColor(R.id.aishang_username, getResources().getColor(R.color.gray_text_color));
                        holder.setText(R.id.aishang_isFirst, "没抢到");
                        holder.setTextColor(R.id.aishang_isFirst, getResources().getColor(R.color.gray_text_color));
                        holder.setTextColor(R.id.aishang_city, getResources().getColor(R.color.gray_text_color));
                        holder.setTextColor(R.id.aishang_price, getResources().getColor(R.color.gray_text_color));
                    }
                    holder.setText(R.id.aishang_username, mainlistdata.getUsername());
                    holder.setText(R.id.aishang_city, mainlistdata.getCity());
                    holder.setText(R.id.aishang_price, "¥" + mainlistdata.getPrice());
                    break;

            }
        }
    }

    public class AdaptListPost extends BaseMultiItemQuickAdapter<Auction_pastedturnover.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptListPost(FragmentActivity context, List<Auction_pastedturnover.ListBean> data, String type) {
            super(data);
            this.mcontext = context;
            this.type = type;
            addItemType(Auction_pastedturnover.ListBean.THREE, R.layout.item_bidhistory);
        }


        @Override
        protected void convert(MyDateViewHolder holder, Auction_pastedturnover.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case Auction_pastedturnover.ListBean.THREE:
                    ObjectUtils.photoCircle(mContext, mainlistdata.getPhoto(), ((ImageView) holder.getView(R.id.item_detail_bidhistoryimg)));

                    if (holder.getLayoutPosition() == 0) {
                        holder.setTextColor(R.id.aishang_username, getResources().getColor(R.color.red));
                        holder.setText(R.id.aishang_isFirst, "抢先");
                        TextView aishang_isFirst = holder.getView(R.id.aishang_isFirst);
                        holder.setTextColor(R.id.aishang_isFirst, getResources().getColor(R.color.red));
                        holder.setTextColor(R.id.aishang_city, getResources().getColor(R.color.red));
                        holder.setTextColor(R.id.aishang_price, getResources().getColor(R.color.red));
                    } else {
                        holder.setTextColor(R.id.aishang_username, getResources().getColor(R.color.gray_text_color));
                        holder.setText(R.id.aishang_isFirst, "没抢到");
                        holder.setTextColor(R.id.aishang_isFirst, getResources().getColor(R.color.gray_text_color));
                        holder.setTextColor(R.id.aishang_city, getResources().getColor(R.color.gray_text_color));
                        holder.setTextColor(R.id.aishang_price, getResources().getColor(R.color.gray_text_color));
                    }
                    holder.setText(R.id.aishang_username, mainlistdata.getUsername());
                    holder.setText(R.id.aishang_city, mainlistdata.getCity());
                    holder.setText(R.id.aishang_price, "¥" + mainlistdata.getPrice());
                    break;

            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(detail_show!=2){
            service = null;
            mcontext.unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
        }
    }
}
